import axios from 'axios'
import { ElMessage, ElLoading } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { getMAC } from '@/utils/getMAC';
// 初始的 API 基础 URL
let storedNetwork = localStorage.getItem('selectedNetwork');
let apiBaseUrl = 'http://47.76.250.92:9998/info';  // 默认值

// 检查是否从 localStorage 获取到了网络信息
let apiBaseUrls = storedNetwork ? `http://${JSON.parse(storedNetwork).api.b_one}/info` : apiBaseUrl; // 如果有存储的 URL 则使用它，否则使用默认值

// 用于更新 baseURL 的函数
export const setApiBaseUrl = (newUrl) => {
  apiBaseUrls = `http://${newUrl.api.b_one}/info`;
  // 更新到 localStorage，确保重启后可以恢复
  const selectedNetwork = JSON.stringify({
    line_code: newUrl.line_code,
    name: newUrl.name,
    api: newUrl.api
  });
  localStorage.setItem('selectedNetwork', selectedNetwork); // 存入 localStorage
}


const instance = axios.create({
  // baseURL: apiBaseUrl,
  withCredentials: false,
})

// 请求拦截器
instance.interceptors.request.use(
  async config => {
    config.baseURL = apiBaseUrls
    const macAddress = await getMAC();
    config = {
      neddLogin: true,
      ...config,
    }

    const userStore = useUserStore()

    if (config.neddLogin) {
      if (userStore.checkLogin()) {

        config.headers['Authorization'] = `TOKEN ` + userStore.token
      }
    }
    config.headers['PLANTCODE'] = userStore.packageJs.plantcode
    config.headers['MAC'] = macAddress

    return config
  },
  error => {
    ElMessage.error('请求超时')
    Promise.reject(error)
  }
)

// 相应拦截器
instance.interceptors.response.use(
  response => {
    const { data, status } = response

    if (status && status == 200) {
      if ([401].includes(data.code)) {
        ElMessage.warning(data.data.msg_lang.text_zh || '账号已过期，请重新登录')
        const userStore = useUserStore()
        userStore.logout()
        // return Promise.reject(data)
      } else if (data.code != 200) {
        ElMessage.error(data.msg_lang.text_zh)
        return Promise.reject(data)
      }

      return data
    } else {

      ElMessage.error('接口错误')
      return Promise.reject(data)
    }
  },
  error => {
    if (error?.response?.status == 401 || error?.response?.status == 400) {
      ElMessage.warning(error?.response?.data?.msg || '账号已过期，请重新登录')
      const userStore = useUserStore()
      userStore.logout()
      return
    } else if (error?.response?.status == undefined) {
      // ElMessage.error('请求超时')
      const userStore = useUserStore()
      userStore.openerrordialog()
    } else {
      ElMessage.error('请求超时')
      // const userStore = useUserStore()
      // userStore.openerrordialog()
    }


    return Promise.reject(error)
  }
)

export const http = instance
export default instance
